﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Web;
using System.IO;
using System.Configuration;

using AFT.Parking.Foundation.Extensions;
using AFT.Parking.Foundation.Utilities;
using System.Drawing;
using System.Runtime.Serialization.Formatters.Binary;
using System.Web.Configuration;

namespace AFT.Parking.Foundation
{
    public class UploadFile
    {
        private static XmlDocument xmlDocument;
        private static string NormalDictionary = "";
        private static string TemporaryDictionary = "";


        /// <summary>
        /// 对剪裁的图进行缩略
        /// </summary>
        /// <param name="appName"></param>
        /// <param name="param"></param>
        /// <param name="imageFile"></param>
        /// <param name="filename"></param>
        /// <param name="filetype"></param>
        /// <returns></returns>
        public static string SaveSmallImage(string appName, object param, string imageFile, string filename,
            string filetype)
        {
            string returnPath = "";
            //加载配置文件
            LoadConfig();
            //根据appName查找该app对应的文件上传配置
            XmlNode appNode = xmlDocument.SelectSingleNode(string.Format("FileConfiguration/App[@Name='{0}']", appName));
            if (appNode != null)
            {
                XmlAttribute dictionaryNameAttribute = appNode.Attributes["DictionaryName"];
                if (dictionaryNameAttribute != null)
                {
                    //获取部分文件路径
                    string dictionaryName = dictionaryNameAttribute.Value.Trim();
                    if (!string.IsNullOrEmpty(dictionaryName) && dictionaryName.ToLower() == "@Custom".ToLower())
                    {
                        dictionaryName = param.ToString();
                    }
                    else
                    {
                        dictionaryName = appName;
                    }
                    //组合文件存放路径
                    string savePath = string.Format("/{0}/{1}/", TemporaryDictionary, dictionaryName);
                    //定义文件存放的物理路径、判断路径是否存在
                    string physicsPath = GetPhysicsPath(savePath);
                    if (!Directory.Exists(physicsPath))
                        Directory.CreateDirectory(physicsPath);
                    //解析File节点
                    XmlNodeList fileNodeList = appNode.SelectNodes("File");
                    if (fileNodeList.Count > 0)
                    {
                        foreach (XmlNode fileNode in fileNodeList)
                        {
                            //获取File节点的相关属性
                            XmlNode extensionNode = fileNode.SelectSingleNode("Extensions");
                            XmlNode sizeNode = fileNode.SelectSingleNode("Size");
                            XmlNode thumbnailNode = fileNode.SelectSingleNode("Thumbnail");
                            XmlNode waterMarkNode = fileNode.SelectSingleNode("WaterMark");
                            if (extensionNode == null || string.IsNullOrEmpty(extensionNode.InnerText.Trim()))
                            {
                                throw new Exception(string.Format("在Name=\"{0}\"的App节点下的File节点中未能找到Entension节点或Extension节点未包含任何值", appName));
                            }
                            if (sizeNode == null || string.IsNullOrEmpty(sizeNode.InnerText.Trim()))
                            {
                                throw new Exception(string.Format("在Name=\"{0}\"的App节点下的File节点中未能找到Size节点或Size节点未包含任何值", appName));
                            }
                            string fileName = filename;
                            string extensionName = filetype;

                            ImgHelper.WaterMark waterMark = ImgHelper.WaterMark.None;
                            ImgHelper.WaterMarkContent waterMarkContent = new ImgHelper.WaterMarkContent();
                            if (waterMarkNode != null)
                            {
                                XmlNode imgNode = waterMarkNode.SelectSingleNode("Img");
                                waterMarkContent.Img = imgNode == null ? "" : imgNode.InnerText.Trim();
                                XmlNode alphaNode = waterMarkNode.SelectSingleNode("Alpha");
                                waterMarkContent.ImgAlpha = alphaNode == null || string.IsNullOrEmpty(alphaNode.InnerText.Trim()) ? 0.1f : (float)Convert.ToDouble(alphaNode.InnerText);
                                XmlNode textNode = waterMarkNode.SelectSingleNode("Text");
                                waterMarkContent.Text = textNode == null ? "" : textNode.InnerText.Trim();
                                XmlNode fontFimilyNode = waterMarkNode.SelectSingleNode("FontFimily");
                                waterMarkContent.FontFimily = fontFimilyNode == null ? "宋体" : fontFimilyNode.InnerText.Trim();
                                XmlNode fontSizeNode = waterMarkNode.SelectSingleNode("FontSize");
                                waterMarkContent.FontSize = fontSizeNode == null || string.IsNullOrEmpty(fontSizeNode.InnerText.Trim()) ? 20f : (float)Convert.ToDouble(fontSizeNode.InnerText);
                                XmlNode argbNode = waterMarkNode.SelectSingleNode("Argb");
                                waterMarkContent.FontArgb = argbNode == null ? "80,125,188,237" : argbNode.InnerText.Trim();
                                if (!waterMarkContent.Text.IsNullOrEmpty() && !waterMarkContent.Img.IsNullOrEmpty())
                                {
                                    waterMark = ImgHelper.WaterMark.Both;
                                }
                                else if (!waterMarkContent.Img.IsNullOrEmpty())
                                {
                                    waterMark = ImgHelper.WaterMark.Image;
                                }
                                else if (!waterMarkContent.Text.IsNullOrEmpty())
                                {
                                    waterMark = ImgHelper.WaterMark.Text;
                                }
                            }
                            //保存原文件
                            extensionName = "." + extensionName;
                            string saveFileName = fileName + extensionName;

                            string TempPath = savePath + saveFileName;

                            //是否需要生成缩略图
                            if (thumbnailNode != null)
                            {
                                XmlAttribute fixedSizeAttribute = thumbnailNode.Attributes["FixedSize"];
                                XmlAttribute qualityAttribute = thumbnailNode.Attributes["Quality"];
                                bool fixedSize = fixedSizeAttribute == null ? true : Convert.ToBoolean(fixedSizeAttribute.Value);
                                int quality = qualityAttribute == null ? 70 : Convert.ToInt32(qualityAttribute.Value);
                                //开始生成缩略图
                                XmlNodeList whNodeList = thumbnailNode.SelectNodes("WH");
                                foreach (XmlNode whNode in whNodeList)
                                {
                                    XmlAttribute whAttribute = whNode.Attributes["Mark"];
                                    string mark = whAttribute == null ? "" : whAttribute.InnerText.Trim();
                                    string whNodeValue = whNode.InnerText.Trim();
                                    if (!string.IsNullOrEmpty(whNodeValue) && !string.IsNullOrEmpty(mark))
                                    {
                                        string[] wh = whNodeValue.Split("*".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                                        if (wh.Length == 2)
                                        {
                                            //XmlAttribute ignoreWaterMarkAttribute = whNode.Attributes["IgnoreWaterMark"];
                                            //bool ignoreWaterMark = ignoreWaterMarkAttribute == null || string.IsNullOrEmpty(ignoreWaterMarkAttribute.Value.Trim()) ? false : Convert.ToBoolean(ignoreWaterMarkAttribute.Value);
                                            //生成新图
                                            Image _tmpImg = Image.FromFile(imageFile);
                                            Rectangle rect = new Rectangle(0, 0, _tmpImg.Width, _tmpImg.Height);

                                            Image newimg = new Bitmap(Convert.ToInt32(wh[0]), Convert.ToInt32(wh[1]));
                                            Graphics obj = Graphics.FromImage(newimg);

                                            Rectangle mbR = new Rectangle(0, 0, Convert.ToInt32(wh[0]), Convert.ToInt32(wh[1]));

                                            GraphicsUnit units = GraphicsUnit.Pixel;

                                            obj.DrawImage(_tmpImg, mbR, rect, units);
                                            newimg.Save(physicsPath + fileName + mark + extensionName);
                                            _tmpImg.Dispose();
                                            newimg.Dispose();
                                            _tmpImg = null;
                                            newimg = null;
                                            obj.Clear(new Color());
                                            obj.Dispose();
                                            
                                            ////
                                            //using (Stream sr = File.Open(imageFile, FileMode.Open, FileAccess.Read))
                                            //{
                                            //    ImgHelper.MakeThumbnail(sr,
                                            //        physicsPath + fileName + mark + extensionName,
                                            //        Convert.ToInt32(wh[0]), Convert.ToInt32(wh[1]), quality, fixedSize,
                                            //        waterMark, waterMarkContent);
                                            //    //ignoreWaterMark ? ImgHelper.WaterMark.None : waterMark
                                            //}
                                        }
                                    }
                                }
                            }
                            returnPath += savePath + saveFileName;
                        }
                    }
                    else
                    {
                        throw new Exception(string.Format("在Name=\"{0}\"的App节点中未能找到File节点", appName));
                    }
                }
                else
                {
                    throw new Exception(string.Format("在Name=\"{0}\"的App节点中未能找到\"DictionaryName\"属性", appName));
                }
            }
            else
            {
                throw new Exception(string.Format("未能找到Name=\"{0}\"的App节点", appName));
            }
            return returnPath.TrimEnd(';');
        }

        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="appName">应用名称</param>
        /// <param name="param">参数（自定义文件存放路径）</param>
        /// <returns></returns>
        public static string Upload(string appName, object param)
        {
            string returnPath = "";
            //加载配置文件
            LoadConfig();
            //根据appName查找该app对应的文件上传配置
            XmlNode appNode = xmlDocument.SelectSingleNode(string.Format("FileConfiguration/App[@Name='{0}']", appName));
            if (appNode != null)
            {
                XmlAttribute dictionaryNameAttribute = appNode.Attributes["DictionaryName"];
                if (dictionaryNameAttribute != null)
                {
                    //获取部分文件路径
                    string dictionaryName = dictionaryNameAttribute.Value.Trim();
                    if (!string.IsNullOrEmpty(dictionaryName) && dictionaryName.ToLower() == "@Custom".ToLower())
                    {
                        dictionaryName = param.ToString();
                    }
                    else
                    {
                        dictionaryName = appName;
                    }
                    //组合文件存放路径
                    string savePath = string.Format("/{0}/{1}/", TemporaryDictionary, dictionaryName);
                    //定义文件存放的物理路径、判断路径是否存在
                    string physicsPath = GetPhysicsPath(savePath);
                    if (!Directory.Exists(physicsPath))
                        Directory.CreateDirectory(physicsPath);
                    //解析File节点
                    XmlNodeList fileNodeList = appNode.SelectNodes("File");
                    if (fileNodeList.Count > 0)
                    {
                        foreach (XmlNode fileNode in fileNodeList)
                        {
                            //获取File节点的相关属性
                            XmlNode extensionNode = fileNode.SelectSingleNode("Extensions");
                            XmlNode sizeNode = fileNode.SelectSingleNode("Size");
                            XmlNode thumbnailNode = fileNode.SelectSingleNode("Thumbnail");
                            XmlNode waterMarkNode = fileNode.SelectSingleNode("WaterMark");
                            if (extensionNode == null || string.IsNullOrEmpty(extensionNode.InnerText.Trim()))
                            {
                                throw new Exception(string.Format("在Name=\"{0}\"的App节点下的File节点中未能找到Entension节点或Extension节点未包含任何值", appName));
                            }
                            if (sizeNode == null || string.IsNullOrEmpty(sizeNode.InnerText.Trim()))
                            {
                                throw new Exception(string.Format("在Name=\"{0}\"的App节点下的File节点中未能找到Size节点或Size节点未包含任何值", appName));
                            }
                            //判断上传文件相关限制
                            int filesCount = HttpContext.Current.Request.Files.Count;
                            if (HttpContext.Current.Request.ContentLength / 1024 > Convert.ToInt32(sizeNode.InnerText) * filesCount)
                            {
                                throw new Exception("上传文件超过规定大小");
                            }
                            List<string> allowFileExtensions = extensionNode.InnerText.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList<string>();
                            for (int i = 0; i < filesCount; i++)
                            {
                                HttpPostedFile httpPostedFile = HttpContext.Current.Request.Files[i];
                                List<string> strList = (from extension in allowFileExtensions
                                                        where string.Format(".{0}", extension).ToLower() == Path.GetExtension(httpPostedFile.FileName).ToLower()
                                                        select extension).ToList();
                                if (strList.Count == 0)
                                {
                                    throw new Exception("上传文件列表中包含不允许上传文件类型");
                                }
                            }
                            //开始上传文件
                            for (int i = 0; i < filesCount; i++)
                            {
                                //获取文件名称、文件扩展名称
                                HttpPostedFile httpPostedFile = HttpContext.Current.Request.Files[i];
                                string fileName = GetFileName();
                                string extensionName = Path.GetExtension(httpPostedFile.FileName).ToLower();

                                //是否需要打水印
                                ImgHelper.WaterMark waterMark = ImgHelper.WaterMark.None;
                                ImgHelper.WaterMarkContent waterMarkContent = new ImgHelper.WaterMarkContent();
                                if (waterMarkNode != null)
                                {
                                    XmlNode imgNode = waterMarkNode.SelectSingleNode("Img");
                                    waterMarkContent.Img = imgNode == null ? "" : imgNode.InnerText.Trim();
                                    XmlNode alphaNode = waterMarkNode.SelectSingleNode("Alpha");
                                    waterMarkContent.ImgAlpha = alphaNode == null || string.IsNullOrEmpty(alphaNode.InnerText.Trim()) ? 0.1f : (float)Convert.ToDouble(alphaNode.InnerText);
                                    XmlNode textNode = waterMarkNode.SelectSingleNode("Text");
                                    waterMarkContent.Text = textNode == null ? "" : textNode.InnerText.Trim();
                                    XmlNode fontFimilyNode = waterMarkNode.SelectSingleNode("FontFimily");
                                    waterMarkContent.FontFimily = fontFimilyNode == null ? "宋体" : fontFimilyNode.InnerText.Trim();
                                    XmlNode fontSizeNode = waterMarkNode.SelectSingleNode("FontSize");
                                    waterMarkContent.FontSize = fontSizeNode == null || string.IsNullOrEmpty(fontSizeNode.InnerText.Trim()) ? 20f : (float)Convert.ToDouble(fontSizeNode.InnerText);
                                    XmlNode argbNode = waterMarkNode.SelectSingleNode("Argb");
                                    waterMarkContent.FontArgb = argbNode == null ? "80,125,188,237" : argbNode.InnerText.Trim();
                                    if (!waterMarkContent.Text.IsNullOrEmpty() && !waterMarkContent.Img.IsNullOrEmpty())
                                    {
                                        waterMark = ImgHelper.WaterMark.Both;
                                    }
                                    else if (!waterMarkContent.Img.IsNullOrEmpty())
                                    {
                                        waterMark = ImgHelper.WaterMark.Image;
                                    }
                                    else if (!waterMarkContent.Text.IsNullOrEmpty())
                                    {
                                        waterMark = ImgHelper.WaterMark.Text;
                                    }
                                }
                                //是否需要生成缩略图
                                if (thumbnailNode != null)
                                {
                                    XmlAttribute fixedSizeAttribute = thumbnailNode.Attributes["FixedSize"];
                                    XmlAttribute qualityAttribute = thumbnailNode.Attributes["Quality"];
                                    bool fixedSize = fixedSizeAttribute == null ? true : Convert.ToBoolean(fixedSizeAttribute.Value);
                                    int quality = qualityAttribute == null ? 70 : Convert.ToInt32(qualityAttribute.Value);
                                    //开始生成缩略图
                                    XmlNodeList whNodeList = thumbnailNode.SelectNodes("WH");
                                    foreach (XmlNode whNode in whNodeList)
                                    {
                                        XmlAttribute whAttribute = whNode.Attributes["Mark"];
                                        string mark = whAttribute == null ? "" : whAttribute.InnerText.Trim();
                                        string whNodeValue = whNode.InnerText.Trim();
                                        if (!string.IsNullOrEmpty(whNodeValue) && !string.IsNullOrEmpty(mark))
                                        {
                                            string[] wh = whNodeValue.Split("*".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                                            if (wh.Length == 2)
                                            {
                                                //XmlAttribute ignoreWaterMarkAttribute = whNode.Attributes["IgnoreWaterMark"];
                                                //bool ignoreWaterMark = ignoreWaterMarkAttribute == null || string.IsNullOrEmpty(ignoreWaterMarkAttribute.Value.Trim()) ? false : Convert.ToBoolean(ignoreWaterMarkAttribute.Value);
                                                ImgHelper.MakeThumbnail(httpPostedFile.InputStream, physicsPath + fileName + mark + extensionName, Convert.ToInt32(wh[0]), Convert.ToInt32(wh[1]), quality, fixedSize, waterMark, waterMarkContent);//ignoreWaterMark ? ImgHelper.WaterMark.None : waterMark
                                            }
                                        }
                                    }
                                }
                                //保存原文件
                                var saveFileName = appName == "AreaShares" ? (fileName + "{0}" + extensionName) : (fileName + extensionName);
                                httpPostedFile.SaveAs(physicsPath + saveFileName);
                                returnPath += savePath + saveFileName + ";";
                            }
                        }
                    }
                    else
                    {
                        throw new Exception(string.Format("在Name=\"{0}\"的App节点中未能找到File节点", appName));
                    }
                }
                else
                {
                    throw new Exception(string.Format("在Name=\"{0}\"的App节点中未能找到\"DictionaryName\"属性", appName));
                }
            }
            else
            {
                throw new Exception(string.Format("未能找到Name=\"{0}\"的App节点", appName));
            }
            return returnPath.TrimEnd(';');
        }

        /// <summary>
        /// 正式保存文件(供WebSite用)
        /// </summary>
        /// <param name="fullName">临时文件全路径，多个文件请使用“,”号隔开</param>
        /// <returns></returns>
        public static string Save(string appName, string fullName)
        {
            string strDBPath = "";
            //加载配置文件
            LoadConfig();

            if (!fullName.IsNullOrEmpty())
            {
                string[] tempFiles = fullName.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                foreach (var obj in tempFiles)
                {
                    if (!obj.MatchesRegex(string.Format(@"^/{0}/.+", TemporaryDictionary)))
                    {
                        // throw new Exception("fullName参数必须为相对临时目录路径");
                    }
                }
                foreach (string obj in tempFiles)
                {
                    //获取临时文件物理路径
                    string strTempPhysicsPath = GetPhysicsPath(obj);

                    //获取持久文件物理路径
                    string strPhysicsPath = GetPhysicsPath(obj.Replace(TemporaryDictionary, NormalDictionary));

                    //获取存入数据库的路径
                    strDBPath += obj.Replace(TemporaryDictionary, NormalDictionary) + ";";

                    //创建目录
                    string strDirectory = strPhysicsPath.Substring(0, strPhysicsPath.LastIndexOf("\\"));
                    if (!Directory.Exists(strDirectory))
                        Directory.CreateDirectory(strDirectory);
                    //文件Copy
                    if (File.Exists(strTempPhysicsPath) && !File.Exists(strPhysicsPath))
                    {
                        File.Copy(strTempPhysicsPath, strPhysicsPath);
                    }

                    #region 缩略图文件Copy

                    //根据appName查找该app对应的文件上传配置
                    XmlNode appNode = xmlDocument.SelectSingleNode(string.Format("FileConfiguration/App[@Name='{0}']", appName));
                    if (appNode != null)
                    {
                        XmlNodeList whNodeList = appNode.SelectNodes("File/Thumbnail/WH");
                        foreach (XmlNode whNode in whNodeList)
                        {
                            XmlAttribute whAttribute = whNode.Attributes["Mark"];
                            if (whAttribute != null)
                            {
                                string mark = whAttribute.InnerText.Trim();
                                if (!string.IsNullOrEmpty(mark))
                                {
                                    string tempThumbnail = GetThumbnail(obj, mark);
                                    string normalThumbnail = tempThumbnail.Replace(TemporaryDictionary, NormalDictionary);
                                    string tempThumbnailPhysicsPath = GetPhysicsPath(tempThumbnail);
                                    string normalThumbnailPhysicsPath = GetPhysicsPath(normalThumbnail);
                                    if (File.Exists(tempThumbnailPhysicsPath) && !File.Exists(normalThumbnailPhysicsPath))
                                    {
                                        File.Copy(tempThumbnailPhysicsPath, normalThumbnailPhysicsPath);
                                    }
                                }
                            }
                        }
                    }
                    #endregion
                }
            }
            else
            {
                throw new Exception("传入的路径为空");
            }
            return strDBPath.TrimEnd(';');
        }

        /// <summary>
        /// 正式保存文件(供桌面应用程序使用)
        /// </summary>
        /// <param name="fullName">临时文件全路径，多个文件请使用“,”号隔开</param>
        /// <returns></returns>
        public static string SaveByCS(string appName, string fullName)
        {
            string strDBPath = "";
            //加载配置文件
            LoadConfig();

            if (!fullName.IsNullOrEmpty())
            {
                string[] tempFiles = fullName.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                foreach (var obj in tempFiles)
                {
                    if (!obj.MatchesRegex(string.Format(@"^/{0}/.+", TemporaryDictionary)))
                    {
                        throw new Exception("fullName参数必须为相对临时目录路径");
                    }
                }
                foreach (string obj in tempFiles)
                {
                    //获取临时文件物理路径
                    string strTempPhysicsPath = GetPhysicsPathByCS(obj);

                    //获取持久文件物理路径
                    string strPhysicsPath = GetPhysicsPathByCS(obj.Replace(TemporaryDictionary, NormalDictionary));

                    //获取存入数据库的路径
                    strDBPath += "," + obj.Replace(TemporaryDictionary, NormalDictionary);

                    //创建目录
                    int pos1 = strPhysicsPath.LastIndexOf("\\");
                    int pos2 = strPhysicsPath.LastIndexOf("/");
                    int pos = pos1 > pos2 ? pos1 : pos2;
                    string strDirectory = strPhysicsPath.Substring(0, pos);
                    if (!Directory.Exists(strDirectory))
                        Directory.CreateDirectory(strDirectory);
                    //文件Copy
                    if (File.Exists(strTempPhysicsPath) && !File.Exists(strPhysicsPath))
                    {
                        File.Copy(strTempPhysicsPath, strPhysicsPath);
                    }

                    #region 缩略图文件Copy

                    //根据appName查找该app对应的文件上传配置
                    XmlNode appNode = xmlDocument.SelectSingleNode(string.Format("FileConfiguration/App[@Name='{0}']", appName));
                    if (appNode != null)
                    {
                        XmlNodeList whNodeList = appNode.SelectNodes("File/Thumbnail/WH");
                        foreach (XmlNode whNode in whNodeList)
                        {
                            XmlAttribute whAttribute = whNode.Attributes["Mark"];
                            if (whAttribute != null)
                            {
                                string mark = whAttribute.InnerText.Trim();
                                if (!string.IsNullOrEmpty(mark))
                                {
                                    string tempThumbnail = GetThumbnail(obj, mark);
                                    string normalThumbnail = tempThumbnail.Replace(TemporaryDictionary, NormalDictionary);
                                    string tempThumbnailPhysicsPath = GetPhysicsPathByCS(tempThumbnail);
                                    string normalThumbnailPhysicsPath = GetPhysicsPathByCS(normalThumbnail);
                                    if (File.Exists(tempThumbnailPhysicsPath) && !File.Exists(normalThumbnailPhysicsPath))
                                    {
                                        File.Copy(tempThumbnailPhysicsPath, normalThumbnailPhysicsPath);
                                    }
                                }
                            }
                        }
                    }
                    #endregion
                }
            }
            else
            {
                throw new Exception("传入的路径为空");
            }
            return strDBPath.Trim(',');
        }

        /// <summary>
        /// 装载配置文件
        /// </summary>
        private static void LoadConfig()
        {
            if (xmlDocument == null)
            {
                FileInfo fileInfo = new FileInfo(string.Format("{0}UploadFile.config", AppDomain.CurrentDomain.BaseDirectory));
                //判断配置文件是否存在
                if (fileInfo.Exists)
                {
                    try
                    {
                        //将配置文件Load进XmlDocument，以便进行相关操作
                        FileStream fileStream = fileInfo.Open(FileMode.Open, FileAccess.Read, FileShare.Read);
                        XmlReader xmlReader = XmlReader.Create(fileStream);
                        xmlDocument = new XmlDocument();
                        xmlDocument.Load(xmlReader);
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
                else
                {
                    throw new Exception("UploadFile.config配置文件不存在");
                }
            }
            //获取NormalDictionary及TemporaryDictionary
            if (string.IsNullOrEmpty(NormalDictionary) || string.IsNullOrEmpty(TemporaryDictionary))
            {
                XmlNode xmlNode = xmlDocument.SelectSingleNode("FileConfiguration");
                if (xmlNode != null)
                {
                    XmlAttribute xmlAttribute = xmlNode.Attributes["NormalDictionary"];
                    if (xmlAttribute != null)
                    {
                        string xmlAttributeValue = xmlAttribute.Value.Trim();
                        if (!string.IsNullOrEmpty(xmlAttributeValue))
                        {
                            NormalDictionary = xmlAttributeValue;
                        }
                        else
                        {
                            throw new Exception("FileConfiguration节点的NormalDictionary属性值不允许为空");
                        }
                    }
                    else
                    {
                        throw new Exception("FileConfiguration节点中不存在NormalDictionary属性");
                    }
                    xmlAttribute = xmlNode.Attributes["TemporaryDictionary"];
                    if (xmlAttribute != null)
                    {
                        string xmlAttributeValue = xmlAttribute.Value.Trim();
                        if (!string.IsNullOrEmpty(xmlAttributeValue))
                        {
                            TemporaryDictionary = xmlAttributeValue;
                        }
                        else
                        {
                            throw new Exception("FileConfiguration节点的TemporaryDictionary属性值不允许为空");
                        }
                    }
                    else
                    {
                        throw new Exception("FileConfiguration节点中不存在TemporaryDictionary属性");
                    }
                }
                else
                {
                    throw new Exception("File.config配置文件中不存在FileConfiguration节点");
                }
            }
        }

        /// <summary>
        /// 获取随机文件名（Guid的Hash值）
        /// </summary>
        /// <param name="fileExtension"></param>
        /// <param name="mark"></param>
        /// <returns></returns>
        private static string GetFileName()
        {
            return Guid.NewGuid().GetHashCode().ToString();
        }

        /// <summary>
        /// 获取文件物理路径
        /// </summary>
        /// <param name="strPath"></param>
        /// <returns></returns>
        private static string GetPhysicsPath(string path)
        {
            return HttpContext.Current.Server.MapPath(path);
        }

        /// <summary>
        /// 获取文件物理路径
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private static string GetPhysicsPathByCS(string path)
        {
            return WebConfigurationManager.AppSettings["FileBaseDirectory"] + path;
        }

        /// <summary>
        /// 删除图片
        /// </summary>
        /// <param name="appName"></param>
        /// <param name="fullName"></param>
        public static void Delete(string appName, string fullName)
        {
            //加载配置文件
            LoadConfig();

            if (!string.IsNullOrEmpty(fullName))
            {
                string[] files = fullName.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

                foreach (var obj in files)
                {
                    //删除主文件
                    string strPhysicsPath = GetPhysicsPath(obj);
                    if (File.Exists(strPhysicsPath))
                    {
                        File.Delete(strPhysicsPath);
                    }
                    //删除附属文件
                    XmlNode appNode = xmlDocument.SelectSingleNode(string.Format("FileConfiguration/App[@Name='{0}']", appName));
                    if (appNode != null)
                    {
                        XmlNodeList whNodeList = appNode.SelectNodes("File/Thumbnail/WH");
                        foreach (XmlNode whNode in whNodeList)
                        {
                            XmlAttribute whAttribute = whNode.Attributes["Mark"];
                            if (whAttribute != null)
                            {
                                string mark = whAttribute.InnerText.Trim();
                                if (!string.IsNullOrEmpty(mark))
                                {
                                    string Thumbnail = GetThumbnail(obj, mark);
                                    string ThumbnailPhysicsPath = GetPhysicsPath(Thumbnail);
                                    if (File.Exists(ThumbnailPhysicsPath))
                                    {
                                        File.Delete(ThumbnailPhysicsPath);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 获取缩略图
        /// </summary>
        /// <param name="fullName">原始文件名</param>
        /// <param name="mark">缩略图标识名称</param>
        /// <returns></returns>
        public static string GetThumbnail(string fullName, string mark)
        {
            string thumbnail = "";

            if (!string.IsNullOrEmpty(fullName) && !string.IsNullOrEmpty(mark))
            {
                string[] files = fullName.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

                foreach (var obj in files)
                {
                    int pos = obj.LastIndexOf(".");
                    thumbnail += string.Format("{0}{1}{2};", obj.Substring(0, pos), mark, obj.Substring(pos, obj.Length - pos));
                }
            }
            return thumbnail.TrimEnd(';');
        }

        /// <summary>
        /// 获取文件存入数据库的路径
        /// </summary>
        /// <param name="fullName">临时文件全路径</param>
        /// <returns></returns>
        public static string GetDbPath(string fullName)
        {
            //加载配置文件
            LoadConfig();

            //获取存入数据库的路径
            string strDBPath = fullName.Replace(TemporaryDictionary, NormalDictionary);

            return strDBPath;
        }
    }
}
